<template>
	<view class="content">
		<image class="userImg" :src="info.headimgurl" />
		<button class="b" style="color: #2755CB; font-size: 14px; background: none; border-color: transparent;"
			open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
			<div>
				<uni-icons type="compose" size="16" color="#2755CB"></uni-icons> 选择头像
			</div>
		</button>
		<input class="n" type="nickname" v-model="info.nickname" placeholder="请输入昵称" />
		<button class="btn" @click="save">保存</button>

	</view>
</template>

<script>
export default {
	data() {
		return {
			info: {},
			n: ''
		}
	},
	onLoad() {
		this.$request({
			url: '/wx/user/getUseInfo',
			method: 'get',
			loading: true,
		}).then(res => {
			this.info = res.data;
		})
	},
	methods: {
		save() {
			let data = {
				avatar: this.info.headimgurl,
				nickName: this.info.nickname
			}
			this.$request({
				url: `/wx/user/updateAvatarAndNickName`,
				method: 'get',
				loading: true,
				data
			}).then(res2 => {
				this.$msg('更新成功');
				setTimeout(() => uni.navigateBack(), 500);
			})
		},
		onChooseAvatar(e) {
			const { avatarUrl } = e.detail;
			console.log(avatarUrl);
			uni.uploadFile({
				url: this.$base + '/attach/upload',
				header: { Authorization: uni.getStorageSync("token") || "" },
				filePath: avatarUrl,
				name: 'file',
				success: (res) => {
					let d = JSON.parse(res.data).data;
					this.info.headimgurl = this.$base+ '/attach/download/'+ d.id;
					// this.save();
				},
				fail: (err) => {
					// 上传失败，传递错误信息
					this.$msg('图片上传失败')
					reject(new Error('上传失败: ' + err));
				},
			});
		}

	}
}
</script>

<style lang="scss">
.content {
	background: #fff;
	padding: 20px;
	height: 100vh;
	text-align: center;
}

.userImg {
	width: 64px;
	height: 64px;
	border: 2px solid #fff;
	border-radius: 8px;
	text-align: center;
	background: #e0effd;
}
.n {
	margin: 20px 0;
	padding: 10px 0;
	border: 1px solid #eee;
}
.btn {
	margin: auto;
	text-align: center;
	padding: 10px;
	line-height: 30px;
	color: #fff;
	background: #2E5BCC;
	border-radius: 30px;
}
.b {
	border: 0 !important;

}
</style>